package com.ihr360.payroll.service.salarytasklet.step.writer;


import com.ihr360.job.core.item.ItemWriter;
import com.ihr360.payroll.dao.ActivePayPeriodRepository;
import com.ihr360.payroll.model.dto.salary.task.period.ActivePayPeriod;
import com.ihr360.payroll.model.dto.salary.task.period.PayPeriodTerm;
import com.ihr360.payroll.type.PeriodState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @author davidwei
 */
@Component
public class ActivePayPeriodWriter implements ItemWriter<ActivePayPeriod> {
    @Autowired
    private ActivePayPeriodRepository activePayPeriodRepository;

    @Override
    public void write(List<? extends ActivePayPeriod> activePayPeriods) throws Exception {
        Optional<? extends ActivePayPeriod> optional = activePayPeriods.stream().findFirst();
        if (optional.isPresent()) {
            ActivePayPeriod payPeriod = optional.get();
            payPeriod.setState(PeriodState.CALCULATED);
            PayPeriodTerm currentTerm = payPeriod.getCurrentTerm();
            if (currentTerm != null) {
                currentTerm.setState(PeriodState.CALCULATED);
                currentTerm.setTaskExecutionSequence(currentTerm.getTaskExecutionSequence() + 1);
            }
            activePayPeriodRepository.save(payPeriod);
        }
    }
}